package com.veromca.transaction.service;

import com.veromca.transaction.mapper.AccountMapper;
import com.veromca.transaction.mapper.SysUserMapper;
import com.veromca.transaction.po.AccountPO;
import com.veromca.transaction.po.SysUserPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description: 编程式事务服务
 * 需要注意在回滚的时候，要确保开启了事物但是未提交，
 * 如果未开启或已提交的时候进行回滚是会在catch里面发生异常！
 * @Author: liusongqing
 * @CreateDate: 2019/12/09
 * @UpdateUser:
 * @UpdateDate:
 * @Copyright:
 * @UpdateRemark:
 * @Version: 0.2
 */
@Service
public class TransactionManagerService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private PropagationBService propagationBService;
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;


    public boolean testTransactionManager(SysUserPO sysUser, List<AccountPO> accounts) {
        /*
         * 手动进行事物控制
         */
        TransactionStatus transactionStatus = null;
        boolean isCommit = false;
        try {
            transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);

            // 新增用户
            sysUserMapper.save(sysUser);
            System.out.println("查询的数据1:" + sysUserMapper.selectOne(sysUser));
            if(sysUser.getAge()<50) {
                sysUser.setAge(sysUser.getAge()+2);
                sysUserMapper.updateByPrimaryKey(sysUser);
                System.out.println("查询的数据2:" + sysUserMapper.selectOne(sysUser));
            }else {
                throw new Exception("模拟一个异常!");
            }
            // 新增账号 insertAccounts 无事务
            propagationBService.insertAccounts(accounts);
            //手动提交
            dataSourceTransactionManager.commit(transactionStatus);
            isCommit= true;
            System.out.println("手动提交事物成功!");
            throw new Exception("模拟第二个异常!");
        } catch (Exception e) {
            //如果未提交就进行回滚
            if (!isCommit) {
                System.out.println("发生异常,进行手动回滚！");
                //手动回滚事物
                dataSourceTransactionManager.rollback(transactionStatus);
            }
            e.printStackTrace();
        }
        return true;
    }
}
